package com.dayang.redbook.auth.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import com.dayang.framework.common.domain.response.Response;
import com.dayang.framework.common.exception.BizException;
import com.dayang.framework.common.exception.CommonResponseCodeEnum;
import com.dayang.redbook.auth.constant.RedisConstants;
import com.dayang.redbook.auth.model.user.vo.SendVerificationCodeReqVO;
import com.dayang.redbook.auth.service.VerificationCodeService;
import com.dayang.redbook.auth.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: dayang
 * @since: 2024/5/23
 * @description:
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     * 发送短信验证码
     * @param
     * @return
     */
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        String phone = sendVerificationCodeReqVO.getPhone();
        String key = RedisConstants.buildVerificationCodeKey(phone);
        /*Boolean isSend = redisTemplate.hasKey(key);
        if (BooleanUtil.isTrue(isSend)){
            throw new BizException(CommonResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }*/
        String verificationCode  = RandomUtil.randomNumbers(6);
        //todo 调用第三方短信发送服务
        log.info("==> 手机号: {}, 已生成验证码: 【{}】", phone, verificationCode );
        // 调用第三方短信发送服务
        // threadPoolTaskExecutor.submit(() -> {
        //     String signName = "阿里云短信测试";
        //     String templateCode = "SMS_154950909";
        //     String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
        //     aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        // });
        redisTemplate.opsForValue().set(key,verificationCode,RedisConstants.VERIFICATION_CODE_TTL, TimeUnit.MINUTES);
        return Response.success();
    }
}
